const app = getApp()

Page({
  data: {
    keyword: '',
    historyList: [],
    hotKeywords: ['热干面', '奶茶', '汉堡', '水饺', '炒饭', '炒面', '披萨', '冰淇淋'],
    searchResult: [],
    loading: false,
    loadingMore: false,
    hasMore: true,
    currentPage: 0,
    pageSize: 10,
    showHistory: true,
    showHot: true,
    showResult: false,
    sortType: 'default', // default, sales, price-asc, price-desc, rating
    filterValues: {
      minPrice: 0,
      maxPrice: 1000,
      minRating: 0,
      categories: []
    },
    showFilter: false,
    categories: []
  },

  onLoad() {
    // 获取搜索历史
    this.loadSearchHistory()
    
    // 获取商品分类
    this.loadCategories()
    
    // 监听页面显示后输入框自动获取焦点
    setTimeout(() => {
      this.setData({
        autoFocus: true
      })
    }, 300)
  },

  // 加载搜索历史
  loadSearchHistory() {
    const historyList = wx.getStorageSync('searchHistory') || []
    this.setData({
      historyList
    })
  },

  // 加载商品分类
  loadCategories() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/categories`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            categories: res.data.data
          })
        }
      }
    })
  },

  // 输入关键词
  onInput(e) {
    this.setData({
      keyword: e.detail.value
    })
  },

  // 清空输入框
  clearKeyword() {
    this.setData({
      keyword: '',
      showHistory: true,
      showHot: true,
      showResult: false
    })
  },

  // 执行搜索
  search(e) {
    let keyword = this.data.keyword
    
    // 如果是点击历史记录或热门搜索
    if (e && e.currentTarget && e.currentTarget.dataset.keyword) {
      keyword = e.currentTarget.dataset.keyword
      this.setData({
        keyword
      })
    }
    
    // 关键词为空不执行搜索
    if (!keyword.trim()) {
      return
    }
    
    // 保存搜索历史
    this.saveSearchHistory(keyword)
    
    // 显示搜索结果，隐藏历史和热门
    this.setData({
      showHistory: false,
      showHot: false,
      showResult: true,
      loading: true,
      currentPage: 0,
      searchResult: []
    })
    
    // 执行搜索请求
    this.fetchSearchResult()
  },

  // 获取搜索结果
  fetchSearchResult(loadMore = false) {
    const { keyword, currentPage, pageSize, sortType, filterValues } = this.data
    
    if (loadMore) {
      this.setData({
        loadingMore: true
      })
    } else {
      this.setData({
        loading: true
      })
    }
    
    // 构建搜索参数
    let url = `${app.globalData.apiBaseUrl}/api/products/search?keyword=${encodeURIComponent(keyword)}&page=${loadMore ? currentPage : 0}&size=${pageSize}`
    
    // 添加排序参数
    if (sortType !== 'default') {
      const [field, order] = sortType.includes('-') ? sortType.split('-') : [sortType, 'desc']
      url += `&sortField=${field}&sortOrder=${order.toUpperCase()}`
    }
    
    // 添加筛选参数
    if (filterValues.minPrice > 0) {
      url += `&minPrice=${filterValues.minPrice}`
    }
    
    if (filterValues.maxPrice < 1000) {
      url += `&maxPrice=${filterValues.maxPrice}`
    }
    
    if (filterValues.minRating > 0) {
      url += `&minRating=${filterValues.minRating}`
    }
    
    if (filterValues.categories && filterValues.categories.length > 0) {
      url += `&categories=${filterValues.categories.join(',')}`
    }
    
    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          const { list, hasNext } = res.data.data
          
          this.setData({
            searchResult: loadMore ? [...this.data.searchResult, ...list] : list,
            currentPage: loadMore ? currentPage + 1 : 1,
            hasMore: hasNext
          })
        } else {
          wx.showToast({
            title: '搜索失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({
          loading: false,
          loadingMore: false
        })
      }
    })
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword.trim()) return
    
    let historyList = wx.getStorageSync('searchHistory') || []
    
    // 如果已存在相同关键词，先删除
    historyList = historyList.filter(item => item !== keyword)
    
    // 添加到历史列表开头
    historyList.unshift(keyword)
    
    // 限制历史记录数量
    if (historyList.length > 10) {
      historyList = historyList.slice(0, 10)
    }
    
    // 保存到本地存储
    wx.setStorageSync('searchHistory', historyList)
    
    // 更新数据
    this.setData({
      historyList
    })
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定清空搜索历史？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory')
          this.setData({
            historyList: []
          })
        }
      }
    })
  },

  // 切换排序方式
  changeSort(e) {
    const { type } = e.currentTarget.dataset
    
    this.setData({
      sortType: type
    })
    
    // 重新搜索
    this.fetchSearchResult()
  },

  // 显示筛选面板
  showFilterPanel() {
    this.setData({
      showFilter: true
    })
  },

  // 隐藏筛选面板
  hideFilterPanel() {
    this.setData({
      showFilter: false
    })
  },

  // 更新筛选价格范围
  setPriceRange(e) {
    const { filterValues } = this.data
    filterValues.minPrice = e.detail.value[0]
    filterValues.maxPrice = e.detail.value[1]
    
    this.setData({
      filterValues
    })
  },

  // 更新最低评分
  setMinRating(e) {
    const { filterValues } = this.data
    filterValues.minRating = e.detail.value
    
    this.setData({
      filterValues
    })
  },

  // 切换分类筛选
  toggleCategory(e) {
    const { id } = e.currentTarget.dataset
    const { filterValues } = this.data
    const index = filterValues.categories.indexOf(id)
    
    if (index > -1) {
      filterValues.categories.splice(index, 1)
    } else {
      filterValues.categories.push(id)
    }
    
    this.setData({
      filterValues
    })
  },

  // 应用筛选
  applyFilter() {
    this.hideFilterPanel()
    this.fetchSearchResult()
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filterValues: {
        minPrice: 0,
        maxPrice: 1000,
        minRating: 0,
        categories: []
      }
    })
  },

  // 查看商品详情
  viewProduct(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/product/detail?id=${id}`
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.showResult) {
      this.fetchSearchResult()
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
    } else {
      wx.stopPullDownRefresh()
    }
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.showResult && this.data.hasMore && !this.data.loadingMore) {
      this.fetchSearchResult(true)
    }
  }
}) 